import { ReactElement, useState, useEffect, useRef } from 'react'
import { Modal, Form, Input, DatePicker, Select, FormInstance, message } from 'antd'
import { getPersonList, addRequest, updateRequest } from './ajax'
import moment, { Moment } from 'moment'
import { awaitWrap } from '@src/assets/js/tool'
import UnitNumberInput from '@components/unitNumberInput'

const { Item } = Form
const { Option } = Select

// 初始化员工列表
async function initPersonList (setPersons: (v: string[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getPersonList())
  if (e === null && d instanceof Array) {
    setPersons(d)
  }
}

interface FormSchema {
  id: string | undefined
  title: string
  date: Moment[]
  principal: string
  people_num: number | undefined
}

// 提交处理
async function submitHandle (d: FormSchema, refreshData: () => void, hide: () => void): Promise<void> {
  const o: { [k: string]: any } = { ...d }
  delete o.date
  const date: Moment[] = d.date
  const begin = moment(`${date[0].format('YYYY-MM')}-01 00:00`)
  const end = moment(`${date[1].format('YYYY-MM')}-01 00:00`)
  end.add(1, 'month')
  end.subtract(1, 'second')
  o.begin_datetime = Math.floor(begin.valueOf() / 1000)
  o.end_datetime = Math.floor(end.valueOf() / 1000)
  let fn = addRequest
  if (typeof o.id === 'string') {
    fn = updateRequest
  }
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(fn(o))
  h()
  if (e === null) {
    refreshData()
    hide()
  }
}

interface Props {
  visible: boolean
  data: { [k: string]: any } | null
  hide: () => void
  refreshData: () => void
}

function Main ({ visible, data, hide, refreshData }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  const [persons, setPersons] = useState<string[]>([])
  useEffect(() => {
    initPersonList(setPersons).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    const c = formRef.current
    if (!visible && c !== null) {
      c.resetFields()
    }
  }, [visible, formRef])
  useEffect(() => {
    const c = formRef.current
    if (visible && data !== null && c !== null) {
      const o: { [k: string]: any } = { ...data }
      if (typeof data.begin_datetime === 'number' && typeof data.end_datetime === 'number') {
        o.date = [moment(data.begin_datetime * 1000), moment(data.end_datetime * 1000)]
      }
      c.setFieldsValue(o)
    }
  }, [data, formRef, visible])
  return (
    <Modal visible={visible} title={data !== null ? '编辑考核' : '新建考核'} maskClosable={false} onCancel={hide} onOk={() => formRef.current?.submit()}>
      <Form ref={formRef} labelCol={{ flex: '148px' }} onFinish={async d => await submitHandle(d, refreshData, hide)}>
        <Item name='id' noStyle><span /></Item>
        <Item name='title' label='考核名称' rules={[{ required: true, message: '考核名称不能为空' }]}>
          <Input placeholder='请输入' allowClear />
        </Item>
        <Item name='date' label='考核时间' rules={[{ required: true, message: '考核时间不能为空' }]}>
          <DatePicker.RangePicker picker="month" style={{ width: '100%' }} />
        </Item>
        <Item name='principal' label='负责人' rules={[{ required: true, message: '负责人不能为空' }]}>
          <Select placeholder='请选择' showSearch>
            {persons.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
          </Select>
        </Item>
        <Item name='pre_accepter_ratio_score' label='去年同期受理均值分'>
          <UnitNumberInput unit='分' precision={2} />
        </Item>
        <Item name='pre_processer_ratio_score' label='去年同期办案均值分'>
          <UnitNumberInput unit='分' precision={2} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
